<template>
  <el-dialog
    v-model="props.dialogVisible"
    :title="props.dialogForm?.title"
    :width="props.dialogForm?.width"
    :show-close="false"
    :destroy-on-close="false"
  >
    <el-form :model="eqForm" :rules="rules" ref="eqFormRef" class="deviceForm">
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="设备编号" prop="deviceNum">
            <el-input
              v-model="eqForm.deviceNum"
              autocomplete="off"
              placeholder="请输入设备编号"
              maxlength="16"
              :disabled="props.dialogForm?.id != ''"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              v-model="eqForm.deviceName"
              autocomplete="off"
              placeholder="请输入设备名称"
              maxlength="16"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="设备类型" prop="deviceType">
            <el-input
              v-model="eqForm.deviceTypeName"
              placeholder="请选择"
              class="input-with-select"
              style="width: 75%"
              @focus="selectType('type')"
            >
            </el-input>
            <el-button
              @click="selectType('type')"
              style="width: 25%"
              type="primary"
              plain
              >选择</el-button
            >
            <span class="tips"
              >新增类型后，可在【企业设置管理-数据字典配置】中管理</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="设备型号">
            <el-input
              v-model="eqForm.modelName"
              autocomplete="off"
              placeholder="请输入设备型号"
              maxlength="16"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="所在部门" prop="deptName">
            <el-input
              v-model="eqForm.deptName"
              placeholder="请选择"
              class="input-with-select"
              style="width: 75%"
              @focus="selectDept()"
            >
            </el-input>
            <el-button
              @click="selectDept()"
              style="width: 25%"
              type="primary"
              plain
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="11" v-if="statusBool">
          <el-form-item label="设备状态" prop="deviceStatus">
            <el-select
              v-model="eqForm.deviceStatus"
              class="m-2"
              style="width: 100%"
              placeholder="请选择"
              :disabled="props.dialogForm?.id == ''"
            >
              <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="位置编号">
            <el-input
              v-model="eqForm.seatNum"
              placeholder="请输入设备位置编号"
              class="input-with-select"
              maxlength="16"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="设备价值">
            <el-input
              v-model="eqForm.deviceCost"
              autocomplete="off"
              style="width: 85%"
              placeholder="请输入设备价值"
              type="text"
              maxlength="8"
              onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
            />
            <div>万元</div>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="设备照片">
            <el-upload
              class="avatar-uploader"
              v-model:file-list="fileList"
              list-type="picture-card"
              :show-file-list="true"
              :class="{ hide: hideUpload }"
              v-loading="uploadLoading"
              accept=".png,.jpg,jpeg"
              :action="`${proxy.$http}/user/upload/uploadFile`"
              :http-request="(resp: any) => { return handleUpload(resp, 13) }"
              :headers="headers"
              :data="{ type: '13' }"
              :auto-upload="true"
              :limit="1"
              :on-error="(resp: any) => { return fileError(resp, 13) }"
              :on-change="handleChange"
              :before-upload="beforeImageUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <img
                v-if="eqForm.devicePicture != ''"
                :src="eqForm.devicePicture"
                class="avatar"
              />
              <el-icon v-else><Plus /></el-icon>
            </el-upload>
            <div class="tips" style="margin: auto auto 0 5px">
              支持png、jpg格式
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="能耗">
            <el-input
              v-model="eqForm.energyConsumption"
              autocomplete="off"
              style="width: 85%"
              placeholder="请输入能耗"
              maxlength="8"
              onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
              type="text"
            />
            <div>KW/h</div>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="购买日期">
            <el-date-picker
              v-model="eqForm.purchaseDate"
              style="width: 100%"
              type="date"
              placeholder="请选择日期"
              size="defult"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="投产日期">
            <el-date-picker
              v-model="eqForm.operationDate"
              type="date"
              style="width: 100%"
              placeholder="请选择日期"
              size="defult"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="使用年限">
            <el-input
              v-model="eqForm.usefulLife"
              placeholder="请输入使用年限"
              class="input-with-select"
              onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^123456789]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-19]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            >
              <template #append> 年 </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="供应商">
            <el-select
              v-model="eqForm.purveyorId"
              class="m-2"
              style="width: 100%"
              placeholder="请选择供应商"
              @change="purChange"
            >
              <el-option
                v-for="item in gyOptions"
                :key="item.id"
                :label="item.factoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="品牌">
            <el-input
              v-model="eqForm.brand"
              autocomplete="off"
              style="width: 100%"
              placeholder="请输入品牌名称"
              maxlength="16"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="elrowClass">
        <el-col :span="11">
          <el-form-item label="厂家">
            <el-input
              v-model="eqForm.manufacturer"
              autocomplete="off"
              style="width: 100%"
              placeholder="请输入厂家名称"
              maxlength="16"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog v-model="picVisible">
      <img
        style="width: 100%"
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
      />
    </el-dialog>
    <EquipmentTypeDialog
      :typeDialog="typeDialog"
      :typeForm="typeForm"
      @toBack="toBack"
      @deviceTypeSub="deviceTypeSub"
    >
    </EquipmentTypeDialog>
    <SelectDeptDialog
      :deptDialog="deptDialog"
      :deptId="deptId"
      @deptSubmit="deptSubmit"
      @toBackDept="toBackDept"
    >
    </SelectDeptDialog>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(eqFormRef)">取消</el-button>
        <el-button type="primary" @click="submit(eqFormRef)" :loading="loading">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ElLoading,
  ElMessage,
  FormInstance,
  FormRules,
  UploadInstance,
  UploadUserFile,
  UploadProps
} from 'element-plus'
import {
  ref,
  reactive,
  defineAsyncComponent,
  watch,
  getCurrentInstance
} from 'vue'
import {
  getPurveyorList,
  addDeviceApi,
  deviceDetailApi,
  editDeviceApi
} from '/@/api/assets/index'
import { uploadFileApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
import { Plus } from '@element-plus/icons-vue'
import { dictionaryList } from '/@/api/publicApi'

const { proxy } = getCurrentInstance() as any
const EquipmentTypeDialog = defineAsyncComponent(
  () => import('./EquipmentTypeDialog.vue')
)
const SelectDeptDialog = defineAsyncComponent(
  () => import('./SelectDeptDialog.vue')
)
const props = defineProps({
  dialogVisible: Boolean,
  dialogForm: Object
})
const emit = defineEmits(['cancel', 'submit'])
const loading = ref(false)
const statusBool = ref(false)
const eqFormRef = ref<FormInstance>()
const eqForm = ref({
  deviceNum: '',
  deviceName: '',
  deviceType: 'a0e3dab0b84a44eebf5469acb4523f51',
  deviceTypeName: '通用设备',
  // modelId: '',
  modelName: '',
  deptId: '',
  deptName: '',
  deviceStatus: '',
  seatNum: '',
  devicePicture: '',
  deviceCost: '',
  energyConsumption: '',
  purchaseDate: '',
  operationDate: '',
  purveyorId: '',
  purveyorName: '',
  brand: '',
  usefulLife: '',
  manufacturer: ''
})
const deptName = ref('')

const validDeptId = (rule: any, value: any, callback: any) => {
  if (deptName.value == '') {
    callback(new Error('请选择所在部门'))
  } else {
    callback()
  }
}
// const getDeviceType = () => {
//   dictionaryList({ configType: 'device_type', keyword: '' }).then(
//     (res: any) => {
//       console.log(res)
//       const defaultItem = res.data.filter(
//         (it: any) => it.configValue === '通用设备'
//       )[0]
//       eqForm.value.deviceType = defaultItem.id
//       eqForm.value.deviceTypeName = defaultItem.configValue
//     }
//   )
// }
// getDeviceType()

const rules = reactive<FormRules>({
  deviceNum: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  deviceType: [
    { required: true, message: '请选择设备类型', trigger: ['blur', 'change'] }
  ],
  deptName: [
    { required: true, message: '请选择所在部门', trigger: 'change' }
    // { required: true, validator: validDeptId }
  ],
  deviceStatus: [
    { required: true, message: '请选择设备状态', trigger: 'change' }
  ]
})

const stateOptions = ref([
  { value: '1', label: '使用中' },
  { value: '2', label: '维修中' },
  { value: '3', label: '维保中' },
  { value: '4', label: '点检中' }
])
const gyOptions = ref([{ id: '', factoryName: '' }])

const typeDialog = ref<boolean>(false)
const typeForm = ref({
  width: '25%',
  title: '',
  voucher: '',
  id: ''
})

//选择设备类型或新增型号
const selectType = (str: string) => {
  typeForm.value.voucher = str
  if (str == 'type') {
    typeForm.value.title = '设备类型选择'
    if (eqForm.value.deviceType != '') {
      typeForm.value.id = eqForm.value.deviceType
    } else {
      typeForm.value.id = ''
    }
    typeDialog.value = !typeDialog.value
  }
}
const toBack = () => {
  typeDialog.value = !typeDialog.value
}
const deviceTypeSub = (val: any) => {
  if (typeForm.value.title == '设备类型选择') {
    eqForm.value.deviceType = val.deviceTypeId
    eqForm.value.deviceTypeName = val.deviceTypeName
  }
  typeDialog.value = !typeDialog.value
}

//选择部门
const deptDialog = ref(false)
const deptId = ref('')
const selectDept = () => {
  if (eqForm.value.deptId != '') {
    deptId.value = eqForm.value.deptId
  } else {
    deptId.value = ''
  }
  deptDialog.value = !deptDialog.value
}
const toBackDept = () => {
  deptDialog.value = !deptDialog.value
}
const deptSubmit = (val: any) => {
  eqForm.value.deptId = val.id
  eqForm.value.deptName = val.name
  deptDialog.value = !deptDialog.value
}

const cancel = (formEl: FormInstance | undefined) => {
  fileList.value = []
  if (!formEl) return
  formEl.resetFields()
  emit('cancel')
}
const submit = async (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (props.dialogForm?.id == '') {
        addDeviceApi(eqForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage.success('新增成功')
            fileList.value = []
            emit('submit')
          }
          loading.value = false
        })
      } else {
        Reflect.set(eqForm.value, 'id', props.dialogForm?.id)
        editDeviceApi(eqForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage.success('编辑成功')
            fileList.value = []
            emit('submit')
          }
          loading.value = false
        })
      }
    } else {
      loading.value = false
    }
  })
}

//图片上传
const uploadLoading = ref<boolean>(false) // 加载效果
const userInfo = Session.get('token')
const token = userInfo ? userInfo : ''
const fileList = ref<UploadUserFile[]>([])
const headers = ref({
  'Content-Type': 'multipart/form-data',
  'Api-User-Token': token
})
const beforeImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
  uploadLoading.value = true
  const testmsg = /^image\/(png|jpg|jpeg)$/.test(rawFile.type)
  if (!testmsg) {
    ElMessage.error('上传格式不正确,只支持png、jpg、jpeg!')
    uploadLoading.value = false
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    proxy.$message.error('图片大小不能超过10M!')
    uploadLoading.value = false
    return false
  }
}

const handleUpload = (file: any, type: any) => {
  uploadLoading.value = true
  uploadFileApi({ type: 13, file: file.file }).then((res) => {
    eqForm.value.devicePicture = res.data.fileIds[0]
    ElMessage.success('图片上传成功！')
    uploadLoading.value = false
  })
}

const fileError = (err: any, type: any) => {
  ElMessage.error('项目文件上传失败！')
}

// 图片上传后隐藏上传按钮
const hideUpload = ref<boolean>(false)
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  if (uploadFile) {
    hideUpload.value = true // 隐藏上传按钮
  }
}

// 删除上传的图片
const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  eqForm.value.devicePicture = ''
  // 删除照片后显示上传按钮
  hideUpload.value = false
}

// 图片预览弹窗
const dialogImageUrl = ref('')
const picVisible = ref(false)
// 图片预览事件
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  picVisible.value = true
}

const getPurveyor = () => {
  getPurveyorList().then((res: any) => {
    if (res.code == 0) {
      gyOptions.value = res.data
    }
  })
}

const purChange = (val: any) => {
  gyOptions.value.forEach((i: any) => {
    if (i.id == val) {
      eqForm.value.purveyorName = i.factoryName
    }
  })
}

watch(
  () => props.dialogVisible,
  () => {
    getPurveyor()
    hideUpload.value = false
    if (props.dialogForm?.id != '') {
      statusBool.value = false
      deviceDetailApi(props.dialogForm?.id).then((res) => {
        if (res.code == 0) {
          eqForm.value.deviceNum = res.data.deviceNum
          eqForm.value.deviceName = res.data.deviceName
          eqForm.value.deviceTypeName = res.data.deviceTypeName
          eqForm.value.deviceType = res.data.deviceType
          eqForm.value.modelName = res.data.modelName
          eqForm.value.deptId = res.data.deptId
          eqForm.value.deptName = res.data.deptName
          eqForm.value.deviceStatus = JSON.stringify(res.data.deviceStatus)
          eqForm.value.seatNum = res.data.seatNum
          eqForm.value.deviceCost = res.data.deviceCost
          eqForm.value.energyConsumption = res.data.energyConsumption
          eqForm.value.devicePicture = res.data.devicePicture
          eqForm.value.purchaseDate = res.data.purchaseDate
          eqForm.value.operationDate = res.data.operationDate
          eqForm.value.purveyorId = res.data.purveyorId
          eqForm.value.purveyorName = res.data.purveyorName
          eqForm.value.brand = res.data.brand
          eqForm.value.usefulLife = res.data.usefulLife
          eqForm.value.manufacturer = res.data.manufacturer
        }
      })
    } else {
      statusBool.value = true
      eqForm.value.deviceNum = ''
      eqForm.value.deviceName = ''
      eqForm.value.deviceTypeName = '通用设备'
      eqForm.value.deviceType = 'a0e3dab0b84a44eebf5469acb4523f51'
      eqForm.value.modelName = ''
      eqForm.value.deptId = ''
      eqForm.value.deptName = ''
      eqForm.value.deviceStatus = '1'
      eqForm.value.seatNum = ''
      eqForm.value.deviceCost = ''
      eqForm.value.energyConsumption = ''
      eqForm.value.devicePicture = ''
      eqForm.value.purchaseDate = ''
      eqForm.value.operationDate = ''
      eqForm.value.purveyorId = ''
      eqForm.value.purveyorName = ''
      eqForm.value.brand = ''
      eqForm.value.usefulLife = ''
      eqForm.value.manufacturer = ''
    }
  },
  { immediate: true }
)
</script>
<style scoped lang="scss">
.elrowClass {
  margin-bottom: 16px;
  justify-content: space-between;
}

.tips {
  font-size: 13px;
  font-weight: 400;
  line-height: 21px;
  color: rgba(140, 140, 140, 1);
  text-align: left;
}

.avatar-uploader .avatar {
  width: 84px;
  height: 84px;
  display: block;
}
</style>
<style>
.el-dialog__title {
  font-size: 20px !important;
  font-weight: 700 !important;
}

.avatar-uploader .el-upload {
  width: 84px;
  height: 84px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 84px;
  height: 84px;
  text-align: center;
}
.hide .el-upload--picture-card {
  display: none;
}

.el-input__wrapper {
  background: white !important;
}

.deviceForm .el-upload-list__item {
  width: 84px !important;
  height: 84px !important;
}
</style>
